from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import mixins, viewsets, status
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response

from ..auth import JWTAuth
from home.models import Answer, Question
from home.serializers import AnswerSerializer
# 解答详情,发布解答, 删除解答, 更新解答
@extend_schema_view(
    list=extend_schema(summary='获取解答列表', tags=['解答'], description='获取解答列表'),
    create=extend_schema(summary='发布解答',tags=['解答'],description='发布解答'),
    retrieve=extend_schema(summary='获取解答详情',tags=['解答'],description='获取解答详情'),
    update=extend_schema(summary='更新解答数据(全量更新)',tags=['解答'],description='更新解答数据(全量更新)'),
    partial_update=extend_schema(summary='更新解答数据(部分更新)',tags=['解答'],description='更新解答数据(部分更新)'),
    destroy=extend_schema(summary='删除解答数据',tags=['解答'],description='删除解答数据'),
    mine=extend_schema(summary='获取当前登录账号数据',tags=['解答'],description='获取当前登录账号发布的解答数据')
)
class AnswerViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,viewsets.GenericViewSet):
    # 设置数据集
    queryset = Answer.objects.all()
    # 设置序列化器
    serializer_class = AnswerSerializer
    # 必须为列表或者元组类型
    authentication_classes = [JWTAuth]
    # 设置路径参数名称, 默认值为pk
    # lookup_url_kwarg = 'uuid'
    # 设置retrieve方法默认查询的字段
    lookup_field = 'uuid'

    # 重写retrieve方法,
    def retrieve(self, request, *args, **kwargs):
        uuid=kwargs.get('uuid')
        answer=Answer.objects.get(uuid=uuid)
        if answer:
            # 阅读次数+1
            answer.visit+=1
            answer.save()
            serializer = AnswerSerializer(answer)
            return Response(data=serializer.data)
        return Response(data={'detail':'数据不存在'},status=status.HTTP_404_NOT_FOUND)

    def perform_create(self, serializer):
        # 获取que_id提问id
        que_id=serializer.validated_data.get('que_id')
        # 更新提问状态: 已解答
        Question.objects.filter(id=que_id).update(status=True)
        # 设置发布者id
        serializer.validated_data['user_id'] = self.request.user.id
        # 保存解答数据
        serializer.save()


    def perform_update(self,serializer):
        # 获取待更新的解答数据
        instance=self.get_object()
        if instance.user.id==self.request.user.id:
            # 执行更新操作
            return serializer.save()
        raise PermissionDenied('暂无更新权限')

    def perform_destroy(self,instance):
        # 判断发布者和当前登录账号是否为同一账号
        if instance.user.id==self.request.user.id:
            # 执行删除操作
            return instance.delete()
        raise PermissionDenied('暂无删除权限')

    # 查询当前登录账号发布过答案数据
    @action(methods=['GET'],detail=False)
    def mine(self,request):
        queryset=Answer.objects.filter(user_id=request.user.id).all()
        # 手动调用序列化器
        serializer=AnswerSerializer(queryset, many=True)
        # 返回响应结果
        return Response(serializer.data)


